<?php

function visitors_update_list($vistors) { 
  $timestamp = time();
  $administratorId = 0;
  
  foreach ($vistors as $v) {
    if ($timestamp - $v['timestamp'] > CFG_PING_INTERVAL) {
      database_remove('visitors', $v['id']);
      $administratorId = $v['administratorId'];
    }
  }
  if ($administratorId != 0) {
    operators_update_visitors_counter($administratorId);
  }
}

function visitors_update($sessionId) {
  $timestamp  = time();
  $ip         = $_SERVER['REMOTE_ADDR'];
  $url        = addslashes($_SERVER['HTTP_REFERER']);
  $agent      = addslashes($_SERVER['HTTP_USER_AGENT']);
  $domain     = parse_url($url, PHP_URL_HOST);
  
  $query  = "INSERT INTO `visitors`(`sessionId`, `ip`, `agent`, `url`, `timestamp`, `domain`, `entryTimestamp`) 
  VALUES('$sessionId', '$ip', '$agent', '$url', $timestamp, '$domain', $timestamp) ON DUPLICATE KEY UPDATE `timestamp`=$timestamp";
  
  $result = database_query($query);
}

function visitors_ping($sessionId) {
  $timestamp  = time(); 
  $query      = "UPDATE `visitors` SET `timestamp` = $timestamp WHERE sessionId = '$sessionId'";
  $result     = database_query($query);
}

function visitors_update_window_state($sessionId, $windowState) {
  $query  = "UPDATE `visitors` SET `windowState` = '$windowState' WHERE `sessionId` = '$sessionId'";
  $result = database_query($query); 
}

function visitors_set_administratorId($sessionId, $domain) {
  $query  = "SELECT * FROM `sites` WHERE `domain` = '$domain'";
  $data   = database_get_assoc($query);
  $query  = "UPDATE `visitors` SET `administratorId` = '{$data[0]["administratorId"]}' WHERE `domain` = '$domain'";
  $result = database_query($query);  

  operators_update_visitors_counter($data[0]['administratorId']);
  return $data[0]['administratorId'];
}

function visitors_add_log($visitor, $url) {
  $data['sessionId']        = $visitor['sessionId'];
  $data['administratorId']  = $visitor['administratorId'];
  $data['url']              = $url;
  $data['datetime']         = date('Y-m-d H:i', time());
  database_insert('visitors_log', $data);
}

function visitors_get_by_session_id($sessionId) {
  $query  = "SELECT * FROM `visitors` WHERE `sessionId` = '$sessionId'";
  $data   = database_get_assoc($query);
  return $data[0];
}

function visitors_get_list() {
  $query  = "SELECT * FROM `visitors`";
  $result = database_query($query);
  $data   = array();
  while ($row = mysql_fetch_assoc($result)) {
    $data[] = $row;
  }
  return $data;
}